(function($){
Drupal.behaviors.chatroom_livesupport = {
  attach: function() {
    $(function() {
      $(".chatroom-livesupport").draggable({ handle: "h2.chatroom-chat-title" });
  
      //Trigger chatroom minimize
      $('.chatroom-livesupport .chatroom-chat-control .action-minimize').click(function() {
        var cid = $(this).parent().attr('id').replace(/^chatroom-chat-control-/, '');
        $('#chatroom-livesupport-' + cid).addClass('minimize').removeClass('maximize');
      });
      //Trigger chatroom maximize
      $('.chatroom-livesupport .chatroom-chat-control .action-maximize').click(function() {
        var cid = $(this).parent().attr('id').replace(/^chatroom-chat-control-/, '');
        $('#chatroom-livesupport-' + cid).addClass('maximize').removeClass('minimize');
      });
      //Trigger chatroom close
      $('.chatroom-livesupport .chatroom-chat-control .action-close').click(function() {
        var cid = $(this).parent().attr('id').replace(/^chatroom-chat-control-/, '');
        $('#chatroom-livesupport-' + cid).remove();
        $.get('/livesupport/close/' + cid, function(){});
      });
      // Trigger chatroom open
      $('li.action-chat').click(function(){
        var cid = $(this).attr('id').replace('chatroom-cid-', '');
        if ($('#chatroom-livesupport-' + cid)) {
          $('#chatroom-livesupport-' + cid).removeClass('element-invisible');
          $('#chatroom-livesupport-' + cid).addClass('maximize').removeClass('minimize');
          return false;
        }
        return true;
      });
      // Add region
      if ($('.region-page-bottom').length == 0) {
        $('body').append($('<div class="region region-page-bottom"></div>'));
      }
      // Sort chatroom
      if ($('.chatroom-livesupport').length > 1) {
        var current_right = 10, current_bottom = 10, z_index = 1000;

        $('.chatroom-livesupport').each(function(index, item){
          if (index != 0) {
            current_right += $(this).width() + 10;
          }
          if (current_right > $(window).width()- $(this).width()) {
            current_bottom += $(this).height() + 10;
            current_right = 10;
          }
          $(this).css('right', current_right + 'px');
          $(this).css('bottom', current_bottom + 'px');
          $(this).css('z-index', z_index--);
        });
      }
    });
  }
};
})(jQuery);